// store/car.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { 
  getCarList, 
  getCarDetail, 
  addToFavorites, 
  removeFromFavorites,
  getFavoriteCars,
  publishCar,
  getUserCars
} from '@/api/car'

export const useCarStore = defineStore('car', () => {
  const carList = ref([])
  const carDetail = ref(null)
  const favorites = ref([])
  const userCars = ref([])
  const loading = ref(false)
  
  // 添加图片路径处理函数
  const getFullImageUrl = (imagePath) => {
    if (!imagePath) {
      console.log('图片路径为空，使用默认图片')
      return '/images/default-car.png'
    }
    
    console.log('处理图片路径:', imagePath)
    
    // 如果已经是完整URL，直接返回
    if (imagePath.startsWith('http') || imagePath.startsWith('//')) {
      return imagePath
    }
    
    // 如果已经是绝对路径（以/开头），直接返回
    if (imagePath.startsWith('/')) {
      return imagePath
    }
    
    // 检查是否是 base64 图片
    if (imagePath.startsWith('data:image')) {
      return imagePath
    }
    
    // 对于数据库中的简单文件名，构建正确路径
    let processedPath = imagePath
    
    // 如果路径中不包含目录，默认放在 cars 目录下
    if (!imagePath.includes('/') && !imagePath.startsWith('images/')) {
      processedPath = `/images/cars/${imagePath}`
    } else if (imagePath.startsWith('images/')) {
      // 如果已经是 images/ 开头，添加斜杠
      processedPath = `/${imagePath}`
    }
    
    console.log('处理后的图片路径:', processedPath)
    return processedPath
  }
  
  // 添加头像路径处理函数
  const getFullAvatarUrl = (avatarPath) => {
    if (!avatarPath) {
      console.log('头像路径为空，使用默认头像')
      return '/images/default-avatar.png'
    }
    
    console.log('处理卖家头像路径:', avatarPath)
    
    // 如果已经是完整URL，直接返回
    if (avatarPath.startsWith('http') || avatarPath.startsWith('//') || avatarPath.startsWith('data:')) {
      return avatarPath
    }
    
    // 如果已经是绝对路径（以/开头），直接返回
    if (avatarPath.startsWith('/')) {
      return avatarPath
    }
    
    // 检查是否是 base64 图片
    if (avatarPath.startsWith('data:image')) {
      return avatarPath
    }
    
    // 对于数据库中的简单文件名，使用API服务
    const timestamp = Date.now()
    return `/api/avatar/${avatarPath}?t=${timestamp}`
  }
  
  const fetchCarList = async (params = {}) => {
    loading.value = true
    try {
      const response = await getCarList(params)
      console.log('API返回的车辆列表数据:', response)
      
      let cars = response.data.cars || response.data
      
      if (!cars || cars.length === 0) {
        console.log('API返回空数据')
        carList.value = []
      } else {
        // 处理图片路径 - 使用新的函数
        cars = cars.map(car => {
          // 处理主图片
          if (car.main_image) {
            car.images = [getFullImageUrl(car.main_image)]
          } else if (car.images && car.images.length > 0) {
            // 如果已经有图片数组，处理每个图片
            car.images = car.images.map(img => {
              if (typeof img === 'string') {
                return getFullImageUrl(img)
              } else if (img.image_url) {
                return getFullImageUrl(img.image_url)
              }
              return img
            })
          } else {
            // 如果没有图片，使用默认图片
            car.images = ['/images/default-car.png']
          }
          return car
        })
        
        console.log('处理后的车辆数据:', cars)
        carList.value = cars
      }
      
      return response
    } catch (error) {
      console.error('获取车辆列表失败:', error)
      carList.value = []
      throw error
    } finally {
      loading.value = false
    }
  }
  
  const fetchCarDetail = async (id) => {
    loading.value = true
    try {
      const response = await getCarDetail(id)
      console.log('API返回的车辆详情数据:', response)
      
      let carData = response.data
      
      if (!carData) {
        console.log('API返回空详情数据')
        carDetail.value = null
      } else {
        // 处理图片路径 - 使用新的函数
        if (carData.images && carData.images.length > 0) {
          carData.images = carData.images.map(img => {
            if (typeof img === 'string') {
              return getFullImageUrl(img)
            } else if (img.image_url) {
              return getFullImageUrl(img.image_url)
            }
            return img
          })
        } else {
          carData.images = ['/images/default-car.png']
        }
        
        // 处理配置数据
        if (!carData.configurations && carData.car_configurations) {
          carData.configurations = carData.car_configurations.map(config => ({
            name: config.config_name,
            available: config.available
          }))
        }
        
        // 处理检测数据
        if (!carData.inspections && carData.car_inspections) {
          carData.inspections = carData.car_inspections.map(inspection => ({
            name: inspection.item_name,
            passed: inspection.passed,
            result: inspection.result_description
          }))
        }
        
        // 处理卖家信息 - 使用新的头像处理函数
        if (carData.seller) {
          console.log('处理卖家头像:', carData.seller.avatar)
          if (carData.seller.avatar) {
            carData.seller.avatar = getFullAvatarUrl(carData.seller.avatar)
          } else {
            carData.seller.avatar = '/images/default-avatar.png'
          }
          console.log('处理后的卖家头像:', carData.seller.avatar)
        }
        
        console.log('处理后的车辆详情数据:', carData)
        carDetail.value = carData
      }
      
      return response
    } catch (error) {
      console.error('获取车辆详情失败:', error)
      carDetail.value = null
      throw error
    } finally {
      loading.value = false
    }
  }
  
  const addFavorite = async (carId) => {
    try {
      await addToFavorites(carId)
      await fetchFavorites()
    } catch (error) {
      throw error
    }
  }
  
  const removeFavorite = async (carId) => {
    try {
      await removeFromFavorites(carId)
      await fetchFavorites()
    } catch (error) {
      throw error
    }
  }
  
  const fetchFavorites = async () => {
    try {
      const response = await getFavoriteCars()
      let favoritesData = response.data.favorites || response.data
      
      // 处理收藏列表的图片路径
      favoritesData = favoritesData.map(car => {
        // 确保有 images 数组
        if (!car.images) {
          car.images = []
        }
        
        // 处理主图片
        if (car.main_image) {
          car.images = [getFullImageUrl(car.main_image)]
        } else if (car.images && car.images.length > 0) {
          // 处理现有的图片数组
          car.images = car.images.map(img => {
            if (typeof img === 'string') {
              return getFullImageUrl(img)
            } else if (img.image_url) {
              return getFullImageUrl(img.image_url)
            }
            return img
          })
        } else {
          // 没有图片时使用默认图片
          car.images = ['/images/default-car.png']
        }
        
        return car
      })
      
      favorites.value = favoritesData
    } catch (error) {
      console.error('获取收藏列表失败:', error)
      favorites.value = []
      throw error
    }
  }

  const fetchUserCars = async () => {
    try {
      const response = await getUserCars()
      userCars.value = response.data.cars || response.data
    } catch (error) {
      throw error
    }
  }
  const fetchRecommendCars = async () => {
    try {
      const response = await getRecommendCars() // 需要新增这个API
      return response.data
    } catch (error) {
      console.error('获取推荐车辆失败:', error)
      throw error
    }
  }
  const publishNewCar = async (carData) => {
    try {
      const response = await publishCar(carData)
      return response
    } catch (error) {
      throw error
    }
  }
  
  return {
    carList,
    carDetail,
    favorites,
    userCars,
    loading,
    fetchCarList,
    fetchCarDetail,
    addFavorite,
    removeFavorite,
    fetchFavorites,
    fetchUserCars,
    publishNewCar
  }
})